/*
 * @copyright: Huang Ding
 * @Author: ding-cx
 * @Date: 2021-03-22 14:42:11
 * @LastEditors: ding-cx
 * @LastEditTime: 2021-03-22 16:09:29
 * @Description: file content
 */

import { Service } from "egg";
import { Op } from "sequelize";

export default class SysOrgService extends Service {
  /** 创建组织机构树结构 */
  async createOrgTree() {
    const menuList = await this.ctx.model.Sys.Org.findAll({
      raw: true,
      where: {},
      order: [
        ["parent_org_id", "asc"],
        // ["id", "asc"],
        ["orders", "asc"],
      ],
    });

    function createRouteItem(item, isRoot = false) {
      return {
        id: item.id,
        parent_org_id: isRoot ? 0 : item.parent_org_id,
        org_name: item.org_name,
        org_code: item.org_code,
        state: item.state,
        orders: item.orders,
        trees: [] as number[],
      };
    }
    // console.log(menuList);
    // 将嵌套的路由对象打平的引用保存起来。
    const menuObjList = {};

    const treeList: any[] = [];
    menuList.forEach((item) => {
      // 根菜单处理
      if (item.parent_org_id === 0) {
        const itemRoute = createRouteItem(item, true);
        itemRoute.trees = [item.id]; //把树路径id挂在每个node上。
        treeList.push(itemRoute);
        //以当前项的id作为键，暂存索引在临时对象中以便后续取用。
        menuObjList[item.id] = itemRoute;
      } else {
        //   如果有上级菜单信息，才能嵌套。
        const parentObj = menuObjList[item.parent_org_id];
        if (parentObj) {
          const itemRoute = createRouteItem(item, false);
          itemRoute.trees = [...parentObj.trees, item.id]; //把树路径id挂在每个node上。

          if (!parentObj.children) {
            parentObj["children"] = [];
          }
          parentObj.children.push(itemRoute);
          menuObjList[item.id] = itemRoute;
        }
      }
    });

    return treeList;
  }

  /** 根据组织机构id list获取列表 */
  async getOrgListByIdList(
    idList: number[] = [],
    page: [number, number] = [20, 0]
  ) {
    const ret = await this.ctx.model.Sys.Org.findAndCountAll({
      raw: false,
      where: {
        id: {
          [Op.in]: idList,
        },
      },
      attributes: {
        include: [
          [
            (this.ctx.model.Sequelize.col(
              "parent_org.org_name"
            ) as unknown) as string,
            "parent_org_name",
          ],
        ],
      },
      limit: page[0],
      offset: page[1],
      include: {
        as: "parent_org",
        model: this.app.model.Sys.Org,
        attributes: [],
      },
    });
    return ret;
  }
}
